<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: 0 }"
      :body-style="{
        paddingTop: '20px',
      }"
      :title="$t('workplace.contentData')"
    >
      <template #extra>
        <a-link @click="() => $router.push('/produce/wineproduction')">{{ $t('workplace.viewMore') }}</a-link>
      </template>
      <Chart height="589px" :option="chartOption" />
    </a-card>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { graphic } from 'echarts';
import useLoading from '@/hooks/loading';
import { queryContentData, ContentDataRecord } from '@/api/dashboard';
import useChartOption from '@/hooks/chart-option';
import { ToolTipFormatterParams } from '@/types/echarts';
import { AnyObject } from '@/types/global';
import { getHomeInfo } from '@/api/producedata';
import dayjs from 'dayjs';

const dataInfo = ref([]);
function graphicFactory(side: AnyObject) {
  return {
    type: 'text',
    bottom: '8',
    ...side,
    style: {
      text: '',
      textAlign: 'center',
      fill: '#4E5969',
      fontSize: 12,
    },
  };
}
const { loading, setLoading } = useLoading(true);
const xAxis = ref<string[]>([]);
const chartsData = ref<number[]>([]);
const graphicElements = ref([
  graphicFactory({ left: '2.6%' }),
  graphicFactory({ right: 0 }),
]);
// 中文月份对照表
const chineseMonths = [
  '一月',
  '二月',
  '三月',
  '四月',
  '五月',
  '六月',
  '七月',
  '八月',
  '九月',
  '十月',
  '十一月',
  '十二月',
];
// 生成动态预设月份数组（到当前月）
const presetMonths = computed(() => {
  const currentMonthIndex = dayjs().month(); // 获取当前月份索引（0-11）
  return chineseMonths.slice(0, currentMonthIndex + 1);
});
const getHomeInfoData = async () => {
  const { code, data } = await getHomeInfo();
  if (code === 200) {
    const statisticsMap = new Map();
    // 2. 遍历原始数据统计
    data.forEach(({ produce_time, produce_bottle }) => {
      const monthIndex = dayjs(produce_time).month(); // 获取月份索引
      const monthName = chineseMonths[monthIndex]; // 转换为中文月份

      // 累加统计值
      statisticsMap.set(
        monthName,
        (statisticsMap.get(monthName) || 0) + produce_bottle
      );
    });

    // 3. 合并预设月份并填充默认值
    let newArray = presetMonths.value.map((month) => ({
      month,
      total: statisticsMap.get(month) || 0, // 无数据时默认为0
    }));
    dataInfo.value = [];
    newArray.forEach((entity) => {
      dataInfo.value.push(entity.total);
    });
    console.log(dataInfo.value);
  }
};
getHomeInfoData();
// 创建响应式月份列表
const monthList = ref([]);
// 获取当前月份并生成列表
const generateMonthList = () => {
  const currentDate = new Date();
  const currentMonthIndex = currentDate.getMonth(); // 0-11 表示 1-12月

  const chineseMonths = [
    '一月',
    '二月',
    '三月',
    '四月',
    '五月',
    '六月',
    '七月',
    '八月',
    '九月',
    '十月',
    '十一月',
    '十二月',
  ];

  // 截取到当前月份（包含当前月）
  monthList.value = chineseMonths.slice(0, currentMonthIndex + 1);
  console.log(monthList.value);
};
generateMonthList();
const { chartOption } = useChartOption(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: monthList.value,
        axisTick: {
          alignWithLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      {
        name: '产量(瓶)',
        type: 'bar',
        barWidth: '60%',
        data: dataInfo.value,
        label: {
          show: true,
          position: 'top', // 标签位置
          color: '#333', // 文字颜色
          fontSize: 14, // 字号
          fontWeight: 'bold', // 字体粗细
          formatter: '{c} 瓶', // 带单位的格式
        },
      },
    ],
  };
});
const fetchData = async () => {
  setLoading(true);
  try {
    // const { data: chartData } = await queryContentDataa();
    let chartData = [
      {
        x: '2025-02-14',
        y: 58,
      },
      {
        x: '2025-02-15',
        y: 81,
      },
      {
        x: '2025-02-16',
        y: 53,
      },
      {
        x: '2025-02-17',
        y: 90,
      },
      {
        x: '2025-02-18',
        y: 64,
      },
      {
        x: '2025-02-19',
        y: 88,
      },
      {
        x: '2025-02-20',
        y: 49,
      },
      {
        x: '2025-02-21',
        y: 79,
      },
    ];

    chartData.forEach((el: ContentDataRecord, idx: number) => {
      xAxis.value.push(el.x);
      chartsData.value.push(el.y);
      if (idx === 0) {
        graphicElements.value[0].style.text = el.x;
      }
      if (idx === chartData.length - 1) {
        graphicElements.value[1].style.text = el.x;
      }
    });
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};
fetchData();
</script>

<style scoped lang="less"></style>
